using System;
using System.Collections.Generic;
using OrangeProject.ReactiveList.Core.Communication;
using OrangeProject.ReactiveList.Core.Entities;

namespace OrangeProject.ReactiveList.Core.Server
{
    public class Gateway
    {
        private ITransportCore _transportCore;
        public Dictionary<String, IRouter<IEntity>> Routers { get; set; } = new Dictionary<string, IRouter<IEntity>>();

        public Gateway(ITransportCore transportCore)
        {
            _transportCore = transportCore;
            
            _transportCore.ReceiveState(receivedBody =>
            {
                var sendingBody = new DataBody()
                {
                    Guid = receivedBody.Guid,
                };
                
                receivedBody.Data.ForEach(receivedState =>
                {
                    var router = Routers[receivedState.Name];
                    
                    if (router != null)
                    {
                        router.receivedBody = receivedBody;
                        router.sendingBody = sendingBody;
                        
                        sendingBody.Data.Add(new StateContainer<IEntity>
                        {
                            Name = receivedState.Name,
                            Created = router.Create(receivedState.Created),
                            Deleted = router.Delete(receivedState.Deleted),
                            Updated = router.Delete(receivedState.Updated),
                        });
                    }
                });
                
                
                _transportCore.SendState(sendingBody, SendTo.Client);
            });
        }
    }
}

